package com.anze.abd.ui.update;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * 图片上传控制器
 * @author hejun
 *
 */
@RestController
public class UploadController {

	//获取上传的文件夹，具体路径参考application.properties中的配置
    @Value("${web.upload-path}")
    private String uploadPath;
 
    //获取图片
    private final ResourceLoader resourceLoader; 
    
    /**
     * 初始化
     * @param resourceLoader
     */
    @Autowired  
    public UploadController(ResourceLoader resourceLoader) {
    	
        this.resourceLoader = resourceLoader;  
    }  
    
    /**
     * 获取本地图片
     * @param filename
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/images")   
    public ResponseEntity<?> getFile(@RequestParam("filename") String filename) {  
        try {  
        	
            return ResponseEntity.ok(resourceLoader.getResource("file:" + Paths.get(uploadPath, filename).toString()));  
        } catch (Exception e) { 
        	
            return ResponseEntity.notFound().build();  
        }  
    }
    
    /**
     * POST请求
     * @param request
     * @param files
     * @return
     */
    //更改为单文件上传
    @RequestMapping("/multi")
    //public ResponseEntity<?> index(HttpServletRequest request,  @RequestParam("files")MultipartFile[] files) {
    public ResponseEntity<?> index(HttpServletRequest request,  @RequestParam("files")MultipartFile[] files,@RequestParam("index")int index) {	

    	//这里可以支持多文件上传
        if(files!=null && files.length>=1) {
        	
            BufferedOutputStream bw = null;
           // String fileName = files[0].getOriginalFilename();
            String fileName = files[index].getOriginalFilename();
            try {
            	
                //判断是否有文件且是否为图片文件
                if(fileName!=null && !"".equalsIgnoreCase(fileName.trim()) && isImageFile(fileName)) {
                	
                	String saveName= UUID.randomUUID().toString()+ getFileType(fileName);
                	//创建输出文件对象
                    File outFile = new File(uploadPath + "/" +saveName );
                    //拷贝文件到输出文件对象
                    //FileUtils.copyInputStreamToFile(files[0].getInputStream(), outFile);
                    FileUtils.copyInputStreamToFile(files[index].getInputStream(), outFile);
                    
                    return new ResponseEntity<Object>(saveName, HttpStatus.OK);
                }
            } catch (Exception e) {
            	
                e.printStackTrace();
            } finally {
                try {
                	
                    if(bw!=null) {bw.close();}
                } catch (IOException e) {
                	
                    e.printStackTrace();
                }
            }
            
        }
//        return "redirect:/index";
        return new ResponseEntity<Object>("please select a file!", HttpStatus.OK);

    }
    
    /**
     * 判断文件是否为图片文件
     * @param fileName
     * @return
     */
    private Boolean isImageFile(String fileName) {
    	
        String [] img_type = new String[]{".jpg", ".jpeg", ".png", ".gif", ".bmp"};
        if(fileName==null) {return false;}
        fileName = fileName.toLowerCase();
        for(String type : img_type) {
            if(fileName.endsWith(type)) {return true;}
        }
        
        return false;
    }

    /**
     * 获取文件后缀名
     * @param fileName
     * @return
     */
    private String getFileType(String fileName) {
    	
        if(fileName!=null && fileName.indexOf(".")>=0) {
            return fileName.substring(fileName.lastIndexOf("."), fileName.length());
        }
        
        return "";
    }
    
    /**
     * ueditor上传配置
     */
    @RequestMapping("/multis")
    public ResponseEntity<?> ueditor(@RequestParam("action") String action,@RequestParam("noCache") String noCache) {  
    	return ResponseEntity.ok("OK");
    }
}